package com.ly.mpayment.persist.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.ly.mpayment.core.util.ReflectionUtils;
import com.ly.mpayment.persist.catstorage.Result;
import com.ly.mpayment.persist.catstorage.Storage;
import com.ly.mpayment.persist.hibernate.PropertyFilter.MatchType;

/**
 * 封装SpringSide扩展功能的Hibernat DAO泛型基类.
 * <p/>
 * 扩展功能包括分页查询,按属性过滤条件列表查询. 可在Service层直接使用,也可以扩展泛型DAO子类使用,见两个构造函数的注释.
 * 
 * 
 * @param <T>
 *            DAO操作的对象类型
 * @param <PK>
 *            主键类型
 */
public class HibernateDao<T, PK extends Serializable> extends
		SimpleHibernateDao<T, PK> {
	@Autowired
	private Storage storage;

	/**
	 * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends
	 * HibernateDao<User, Long>{ }
	 */
	public HibernateDao() {
		super();
	}

	/**
	 * 用于省略Dao层, Service层直接使用通用HibernateDao的构造函数. 在构造函数中定义对象类型Class. eg.
	 * HibernateDao<User, Long> userDao = new HibernateDao<User,
	 * Long>(sessionFactory, User.class);
	 */
	public HibernateDao(final SessionFactory sessionFactory,
			final Class<T> entityClass) {
		super(sessionFactory, entityClass);
	}

	// 分页查询函数 //

	/**
	 * 分页获取全部对象.
	 */
	public Page<T> getAll(final Page<T> page) {
		return find(page);
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数.不支持其中的orderBy参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            数量可变的查询参数,按顺序绑定.
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Page<T> find(final Page<T> page, final String hql,
			final Object... values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}
		
		setPageParameter(q, page);
		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数.(不支持orderBy参数)
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            命名参数,按名称绑定.
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Page<T> find(final Page<T> page, final String hql,
			final Map<String, Object> values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}

		setPageParameter(q, page);

		List result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param criterions
	 *            数量可变的Criterion.
	 * @return 分页查询结果.附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Page<T> find(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);

		if (page.isAutoCount()) {
			int totalCount = countCriteriaResult(c);
			page.setTotalCount(totalCount);
		}

		setPageParameter(c, page);
		List result = c.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameter(final Query q, final Page<T> page) {
		// hibernate的firstResult的序号从0开始
		q.setFirstResult(page.getFirst() - 1);
		q.setMaxResults(page.getPageSize());
		return q;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria setPageParameter(final Criteria c, final Page<T> page) {
		// hibernate的firstResult的序号从0开始
		c.setFirstResult(page.getFirst() - 1);
		c.setMaxResults(page.getPageSize());

//		if (page.isOrderBySetted()) {
//			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
//			String[] orderArray = StringUtils.split(page.getOrder(), ',');
//
//			Assert.isTrue(orderByArray.length == orderArray.length,
//					"分页多重排序参数中,排序字段与排序方向的个数不相等");
//
//			for (int i = 0; i < orderByArray.length; i++) {
//				if (Page.ASC.equals(orderArray[i])) {
//					c.addOrder(Order.asc(orderByArray[i]));
//				} else {
//					c.addOrder(Order.desc(orderByArray[i]));
//				}
//			}
//		}
		return c;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * <p/>
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Object... values) {
		long count = 0;
		String fromHql = hql;
		// select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;

		try {
			count = findLong(countHql, values);
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
		return count;
	}

	/**
	 * 执行count查询获得总记录数
	 * 
	 * @param hql
	 *            - 查询hql
	 * @param parms
	 *            - 按命名参数进行绑定
	 * @return 总记录数
	 */
	public long findCountResult(final String hql,
			final Map<String, Object> parms) {
		long count = 0;
		String fromHql = hql;
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		try {
			count = (Long) countQuery(fromHql, parms).uniqueResult();
		} catch (HibernateException e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ fromHql, e);
		}

		return count;

	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * <p/>
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql,
			final Map<String, Object> values) {
		Map<String, Object> params = new HashMap<String, Object>(values);
		long count = 0;
		String fromHql = hql;
		// select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;
		// 查询总数时，去掉分页
		params.remove("start");
		params.remove("limit");
		try {
			count = findLong(countHql, params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}

		return count;
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected int countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		@SuppressWarnings("unused")
		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl,
					"orderEntries");
			ReflectionUtils
					.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:", e);
		}

		// 执行Count查询
		int totalCount = (Integer) c.setProjection(Projections.rowCount())
				.uniqueResult();

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			// ReflectionUtils.setFieldValue(impl, "orderEntries",
			// orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:", e);
		}

		return totalCount;
	}

	// 属性过滤条件查询函数 //

	/**
	 * 按属性查找对象列表,支持多种匹配方式.
	 * 
	 * @param matchType
	 *            匹配方式,目前支持的取值为"EQUAL"与"LIKE".
	 */
	public List<T> findBy(final String propertyName, final Object value,
			final MatchType matchType) {
		Criterion criterion = buildPropertyFilterCriterion(propertyName, value,
				matchType);
		return find(criterion);
	}

	/**
	 * 按属性过滤条件列表查找对象列表.
	 */
	public List<T> find(List<PropertyFilter> filters) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return find(criterions);
	}

	/**
	 * 按属性过滤条件列表分页查找对象.
	 */
	public Page<T> find(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return find(page, criterions);
	}

	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildPropertyFilterCriterions(
			final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			String propertyName = filter.getPropertyName();

			boolean multiProperty = StringUtils.contains(propertyName,
					PropertyFilter.OR_SEPARATOR);
			if (!multiProperty) { // properNameName中只有一个属性的情况.
				Criterion criterion = buildPropertyFilterCriterion(
						propertyName, filter.getValue(), filter.getMatchType());
				criterionList.add(criterion);
			} else {// properName中包含多个属性的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				String[] params = StringUtils.split(propertyName,
						PropertyFilter.OR_SEPARATOR);

				for (String param : params) {
					Criterion criterion = buildPropertyFilterCriterion(param,
							filter.getValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}

	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildPropertyFilterCriterion(final String propertyName,
			final Object value, final PropertyFilter.MatchType matchType) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;

		if (MatchType.EQ.equals(matchType)) {
			criterion = Restrictions.eq(propertyName, value);
		}
		if (MatchType.LIKE.equals(matchType)) {
			criterion = Restrictions.like(propertyName, (String) value,
					MatchMode.ANYWHERE);
		}

		return criterion;
	}

	/**
	 * 判断对象的属性值在数据库内是否唯一.
	 * <p/>
	 * 在修改对象的情景下,如果属性新修改的值(value)等于属性原来的值(orgValue)则不作比较.
	 */
	public boolean isPropertyUnique(final String propertyName,
			final Object newValue, final Object oldValue) {
		if (newValue == null || newValue.equals(oldValue))
			return true;
		Object object = findByUnique(propertyName, newValue);
		return (object == null);
	}

	/**
	 * ************基于仓库猫的查询***************************************
	 */
	public List<T> findByNamed(String name, Map<String, Object> parameters) {
		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(name, parameters);
		return this.find(statement.toString(), parameters);
	}


	/**
	 * 分页查询；hql从json文件中读取
	 * 
	 * @param name
	 * @param parameters
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public Page<T> findPageByNamed(String hql, Map<String, Object> parameters,
			int start, int pageSize) {
//		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(hql, parameters);
		// 去掉可能存在的order by、group by子句
		hql = StringUtils.substringBefore(statement.count(), "order by");
		hql = StringUtils.substringBefore(hql, "group by");
		long totalResult = (Long) queryStatistics(hql, parameters);
		parameters.put("start", start * pageSize  > totalResult ? (start - 1) * pageSize : start * pageSize );
		parameters.put("limit", pageSize);
		Page<T> page = new Page<T>(start,start / pageSize + 1, pageSize, totalResult,
				this.find(statement.toString(), parameters));
		return page;
	}

	
	/**
	 * 分页查询；hql从json文件中读取
	 * 
	 * @param name
	 * @param parameters
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public Page<T> findPageByNamedNotCount(String hql, Map<String, Object> parameters,
			int start, int pageSize) {
//		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(hql, parameters);
		// 去掉可能存在的order by、group by子句
		hql = StringUtils.substringBefore(statement.count(), "order by");
		hql = StringUtils.substringBefore(hql, "group by");
		long totalResult = (Long) queryStatistics(hql, parameters);
		parameters.put("start", start * pageSize  > totalResult ? (start - 1) * pageSize : start * pageSize );
		parameters.put("limit", pageSize);
		Page<T> page = new Page<T>(start,start / pageSize + 1, pageSize, totalResult,
				this.find(statement.toString(), parameters));
		return page;
	}
	
	/**
	 * 分页查询；hql从json文件中读取
	 * 
	 * @param name
	 * @param parameters
	 * @return
	 */
	public Page<T> findPageByNamed(String name, Map<String, Object> parameters) {
		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(name, parameters);
		long totalResult = (Long) queryStatistics(statement.count(), parameters);
		int start = (Integer) parameters.get("start");
		int pageSize = (Integer) parameters.get("limit");
		return new Page<T>(start,start / pageSize + 1, pageSize, totalResult, this
				.find(statement.toString(), parameters));
	}

	/**
	 * 分页查询；hql从json文件中读取
	 * 
	 * @param name
	 * @param parameters
	 * @return
	 */
	public List<T>  findNameAll(String name, Map<String, Object> parameters) {
//		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(name, parameters);
		return  this.find(statement.toString(), parameters);
	}
	
	/**
	 * 执行更新或删除操作；hql从json配置文件读取
	 * 
	 * @param name
	 *            json中配置的hql名
	 * @param parameters
	 */
	public int updateByNamed(String name, Map<String, Object> parameters) {
		Assert.hasLength(name, "没有找到指定的预定义语句");
		Result statement = storage.get(name, parameters);
		Query update = this.createQuery(statement.toString(), parameters);
		int i =update.executeUpdate();
		return i;
	}

	public void deleteByIds(String name, String[] ids) {

		Result hql = storage.get(name, new HashMap<String, Object>());
		this.deleteQuery(hql.toString(), ids);

	}
	
	
	public T findOneObject(String hql,final Object... values){
		Query query = this.createQuery(hql);
	 	if (values != null) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
	 	List list = query.list();
	 	if(list != null && list.size() > 0){
	 		return (T) list.get(0);
	 	}
	    return null;
	}

	/**
	 * 执行更新或删除操作；hql从json配置文件读取
	 * 
	 * @param name
	 *            json中配置的hql名
	 * @param name
	 */
	public void updateByNamed(String name) {
		this.updateByNamed(name, null);
	}

	/*************************************************************************/

	/**
	 * 统计查询
	 * 
	 * @param statStatenemt
	 *            统计查询语句
	 * @param parameters
	 *            参数
	 * @return 查询结果
	 * @since 0.3
	 */
	@SuppressWarnings("rawtypes")
	private Object queryStatistics(final String statStatenemt,
			final Map<String, Object> parameters) {
		String hql = statStatenemt.replaceAll("fetch", "");
		Query query = this.getSession().createQuery(hql);
		for (Map.Entry<String, Object> stringObjectEntry : parameters
				.entrySet()) {
			Map.Entry<String, Object> entry = stringObjectEntry;
			if (entry.getValue() != null) {
				if (!entry.getKey().equalsIgnoreCase("start")
						&& !entry.getKey().equalsIgnoreCase("limit"))
					if(entry.getValue().getClass().getName().equals(ArrayList.class.getName())){
                		List list = new ArrayList();
                		list = (List) entry.getValue();
                		query.setParameterList(clearSymbol(entry.getKey()), list);
                	}else{
                		query.setParameter(clearSymbol(entry.getKey()), entry.getValue());                    		
                	}
			}
		}
		return query.uniqueResult();
	}

	/**
	 * 去除参数上的预定义符号
	 * 
	 * @param param
	 *            参数
	 * @return 处理好的参数
	 * @since 0.3
	 */
	private String clearSymbol(String param) {
		return param.replaceAll("^\\:", "");
	}

	/**
	 * 根据id值删除数据,不使用json 根据IDs删除多个对象
	 * 
	 * @param hql
	 * @param ids
	 */
	public void deleteByIds(String hql, String ids) {
		this.deleteQuery(hql.toString(), ids);
	}
}
